package com.zj.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PersistentChatMemoryStore implements ChatMemoryStore {
    private static final String REDIS_KEY_PREFIX = "chat_memory:";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;//redis的操作模板类
    public PersistentChatMemoryStore(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    private String getKey(Object memoryId) {
        return REDIS_KEY_PREFIX + memoryId;
    }
    /**
     * 从redis中获取会话的上下文信息
     * @param memoryId 会话id
     * @return 会话的上下文信息
     */
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String key = getKey(memoryId);
        String messagesJson = redisTemplate.opsForValue().get(key);
        if (messagesJson == null || messagesJson.isEmpty()) {
            return List.of();
        }
        return ChatMessageDeserializer.messagesFromJson(messagesJson);
    }
    /**
     * 向redis中存储会话的上下文信息
     * @param memoryId 会话id
     * @param list 会话的上下文信息
     */
    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        String key = getKey(memoryId);
        String messagesJson = ChatMessageSerializer.messagesToJson(list);
        redisTemplate.opsForValue().set(key, messagesJson);
    }
    /**
     * 删除redis中会话的上下文信息
     * @param memoryId 会话id
     */
    @Override
    public void deleteMessages(Object memoryId) {
        String key = getKey(memoryId);
        redisTemplate.delete(key);
    }
}
